<template>
  <div class="home overflowY">
    <div class="PageContent" v-loading="loading">
      <el-form
        :model="ruleForm"
        :inline="true"
        ref="homeRuleForm"
        :rules="rules"
        class="demo-ruleForm"
        :disabled="saveFlag"
        @submit.native.prevent
      >
        <div class="PageItem margintop20">
          <el-row class="paddingleft2em">
            <el-form-item label="寄存编号" style="margin-bottom: 0">
              <el-input
                v-model="businessCode"
                ref="homebusinessCode"
                @keyup.enter.native="searchData"
                :maxlength="20"
                placeholder="请输入业务编码"
              >
                <el-button
                  type="primary"
                  slot="append"
                  icon="el-icon-search"
                  @click="searchData"
                ></el-button>
              </el-input>

              <el-button type="primary" :disabled="saveFlag">扫描</el-button>
<!--              <el-button type="primary" :disabled="saveFlag">选择</el-button>-->
            </el-form-item>
          </el-row>
        </div>
        <div class="PageItem PageItem1">
          <el-row class="PageInfo"> <i class="info-bar"></i>寄存位置</el-row>
          <el-row class="paddingleft2em">
            <el-form-item label="寄存类型">
              <el-input
                autocomplete="off"
                :value="ruleForm.depositType"
                style="border: 0px"
              ></el-input>
            </el-form-item>
            <el-form-item label="寄存位置">
              <el-input
                class="w425"
                placeholder="请填写寄存位置"
                :value="ruleForm.positionName"
              ></el-input>
            </el-form-item>
            <!-- <el-button
              type="primary"
              :disabled="saveFlag"
              @click="dialogVisible = true"
              >选择寄存格位</el-button
            > -->
          </el-row>
          <el-row class="paddingleft2em">
            <el-form-item label="备注">
              <el-input
                class="w1230"
                placeholder="请填写备注"
                :value="ruleForm.remark"
              ></el-input>
            </el-form-item>
          </el-row>
        </div>
        <DepositInformationDisplay
          identification="handle"
          :ruleForm="ruleForm"
        />

        <div class="PageItem">
          <el-row class="PageInfo"> <i class="info-bar"></i>寄存信息</el-row>
          <el-row class="paddingleft2em">
            <el-form-item label="寄存开始日期" label-width="120px">
              <el-date-picker
                v-model="ruleForm.startDate"
                type="date"
                placeholder="选择日期"
                class="w150"
                @change="Timechange(ruleForm.startDate)"
              ></el-date-picker>
            </el-form-item>

            <el-form-item label="单位" prop="renewUnit">
              <el-radio v-model="ruleForm.renewUnit" label="年">年</el-radio>
              <el-radio v-model="ruleForm.renewUnit" label="月">月</el-radio>
            </el-form-item>
            <el-form-item label="寄存数量" prop="renewNumber">
              <el-input
                v-model.number="ruleForm.renewNumber"
                maxlength="20"
                placeholder="请填写寄存数量"
                @blur="DepositQuantity(ruleForm.renewNumber)"
              ></el-input>
            </el-form-item>
            <el-form-item label="寄存结束日期" label-width="120px">
              <el-date-picker
                v-model="ruleForm.endDate"
                type="date"
                placeholder="选择日期"
                class="w150"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="寄存金额" prop="itemCharge">
              <el-input
                v-model="ruleForm.itemCharge"
                onkeyup="value=value.replace(/[^\d]/g,'')"
                maxlength="11"
                placeholder="请填写联系电话"
              ></el-input>
            </el-form-item>
          </el-row>
        </div>
        <DepositFee
          :tableData="this.tableData"
          :businessCode="this.ruleForm.businessCode"
          :dbid="this.ruleForm.dbId"
          @input="tableData = $event"
          :showList="chargeItems"
          :showListStatus="showListStatus"
        />

        <el-row
          class="PageItem"
          :gutter="30"
          style="text-align: right; margin: 30px 0"
        >
          <el-button type="primary" @click="Save()" :disabled="saveFlag"
            >保存</el-button
          >
        </el-row>
      </el-form>
    </div>
    <div style="width: 0px; height: 0px; overflow: hidden">
      <object id="view1" type="application/x-eloamplugin" name="view"></object>
    </div>
    <div id="idCardContainer"></div>
  </div>
</template>

<script>
import * as Type from "@/api/service";
import { dataFormate, dataFormatetmd } from "@/utils/index";
import DepositInformationDisplay from "@/components/DepositInformationDisplay";
import DepositFee from "@/components/DepositInformationDisplay/DepositFee";
import IdCard from "@/api/IdCard_SS628_100_001U";
import { mapGetters } from "vuex";
export default {
  name: "home",
  props: {
    //自定义模板清除属性
    clearable: {
      type: Boolean,
      default: true,
    },
  },
  components: {
    // StorageCellDialog,
    DepositInformationDisplay,
    DepositFee,
  },
  data() {
    const _self = this;
    return {
      dialogVisible: false, //格位弹框
      dialogTableVisible: false, //寄存费用弹框
      loading: false,
      btnPermisson: {}, //输入业务编码
      value: true,
      form: {
        //弹框表单
      },
      depositCasePrice: "",
      ruleForm: {
        radio: "",
        businessCode: "",
        //寄存位置
        depositTypeCode: "", //寄存类型code
        depositType: "", //寄存类型
        positionName: "", //寄存位置
        remark: "", //备注
        depositCaseId: "", //寄存格位id
        //寄存联系人
        familyName: "",
        certificateType: "",
        certificateNo: "",
        familyGenderCode: "",
        familyAge: "",
        familyPhone: "",
        familyAddress: "",
        DepositLocation: {},
        DepositContact: {},
        //寄存骨灰信息
        depositDeadItems: [],
        //寄存信息
        startDate: "",
        endDate: "",
        renewUnit: "string",
        renewNumber: 0,
        itemCharge: 0,
      }, //按钮权限
      btnRight: {
        btnBusinessCodeScanning: false,
        btnAddFuneralBusiness: false,
        btnReadDeadIdentityCard: false,
        btnReadFamilyMemberIdentityCard: false,
        btnReadFamilyAgentIdentityCard: false,
        btnSaveFuneralBusiness: false,
        btnSaveJumpServiceNegotiation: false,
        btnPhotoArchival: false,
        btnPrintQRCode: false,
      }, //业务编码
      businessCode: "",

      rules: {
        renewUnit: [{ required: true, message: "请选择单位", trigger: "blur" }],
        itemCharge: [
          { required: true, message: "请输入寄存金额", trigger: "blur" },
        ],
      },
      dictionary: {}, //字典
      copydictionary: {}, //用于检索拼音
      negotiator_user: [], //洽谈员单独读取
      selectedOptions: [],
      modify: true, //新增时为true
      new_photolimit: false, //新增时为true
      streetlist: [], //街道列表
      villagelist: [], //村列表
      saveFlag: false, //保存过程中不可更改,true为正在保存
      //省市区县数据
      options: [],
      option: [],
      agetype: 1, //年龄类型
      ageWeizhiFlag: 0,
      cremationType: 0, //遗体类型
      photoBtnlimt: false, //初次保存前，“拍照备案”和“打印逝者二维码”按钮禁用
      onpresscTime: 0, //  阻止短时间内连续点击
      timeint: null,
      tableData: [],
      chargeItems: [],
      showListStatus: true,
    };
  },
  created() {
    //读取路由传过来的参数,优先启用参数传过来的
    let code = this.$route.params.businessCodeParam;
    if (code != null) {
      this.businessCode = code;
      this.ReadData();
    } else if (this.$store.getters.businessCode) {
      this.businessCode = this.$store.getters.businessCode;
      this.ReadData();
    }
  },
  mounted() {
    //按钮权限
    // this.btnRight = this.$route.meta.buttons;
    // //遍历属性赋值将true与false字符串转换成布尔型的值
    // for (var key of Object.keys(this.btnRight)) {
    //   this.btnRight[key] =
    //     this.btnRight[key] || this.btnRight[key] == "true" ? true : false;
    // }
    // //加载洽谈员
    // // this.loaduserwithtypecode();
    // // 初始化高拍仪设备
    // //GPY_S620A3XR.camera.load();
    // //加载数据字典
    // //没有数据，加载数据
    // this.$store
    //   .dispatch("user/getdictionary")
    //   .then((res) => {
    //     //获取字典数据
    //     this.dictionary = res;
    //     this.copydictionary = JSON.parse(JSON.stringify(this.dictionary));
    //     this.$set(this.dictionary, res);
    //     //获取未知的code
    //     if (
    //       this.copydictionary.age_type &&
    //       this.copydictionary.age_type.length
    //     ) {
    //       this.copydictionary.age_type.forEach((item) => {
    //         if (item.dataText == "未知") {
    //           this.ageWeizhiFlag = item.dataCode;
    //         }
    //       });
    //     }
    //     /*判断遗体类型*/
    //     if (
    //       this.copydictionary.cremation_type &&
    //       this.copydictionary.cremation_type.length
    //     ) {
    //       this.copydictionary.cremation_type.forEach((item) => {
    //         if (item.dataText.indexOf("遗体") > -1) {
    //           this.cremationType = item.dataCode;
    //         }
    //       });
    //     }
    //   })
    //   .catch(() => console.log("promise catch err"));
    // //加载省市区县数据
    // // this.loadprovince();
    // //点击文本就让它自动点击前面的input就可以触发选择。但是因组件阻止了冒泡，暂时想不到好方法来触发。
    // //这种比较耗性能，暂时想不到其他的，能实现效果了。
    // this.timeint = setInterval(function () {
    //   var arry = document.querySelectorAll(".el-cascader-node__label");
    //   for (var n = 0; n < arry.length; n++) {
    //     var item = arry[n];
    //     item.onclick = function () {
    //       if (this.previousElementSibling) this.previousElementSibling.click();
    //     };
    //   }
    // }, 1000);
    // // 新语法hook代码更简洁，相当于下面   beforeDestroy  的逻辑
    // this.$once("hook:beforeDestroy", () => {
    //   if (this.timeint) {
    //     console.log("清除定时器");
    //     clearInterval(this.timeint);
    //   }
    // });
  },
  computed: {
    //计算
  },

  methods: {
    // -------弹框相关函数------------------
    determine(e) {
      console.log(e, 666);
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      console.log(this.multipleSelection);
    },
    clearSelection() {
      console.log(this.multipleSelection);
      if (this.title === "寄存费用新增") {
        this.$refs.multipleTable.clearSelection();
        this.dialogTableVisible = false;
      } else {
        this.dialogTableVisible = false;
      }
    },
    newExpenses(express) {
      if (express === "add") {
        this.dialogTableVisible = true;
        this.title = "寄存费用新增";
      } else {
        this.dialogTableVisible = true;
        this.title = "寄存修改";
      }
    },
    // ---------------时间处理相关函数------------------------
    Timechange(starttime) {
      if (this.ruleForm.renewUnit === "年") {
        var date = new Date(this.ruleForm.startDate);
        var year = date.getFullYear();
        year += this.ruleForm.renewNumber;
        var month = (date.getMonth(this.ruleForm.startDate) + 1)
          .toString()
          .padStart(2, "0"); //
        var day = date
          .getDate(this.ruleForm.startDate)
          .toString()
          .padStart(2, "0"); //; // 获取日期
        this.ruleForm.endDate = year + "-" + month + "-" + day;
      } else if (this.ruleForm.renewUnit === "月") {
        var date = new Date(this.ruleForm.startDate);
        var year = date.getFullYear();
        var month = date.getMonth(this.ruleForm.startDate) + 1;
        month += this.ruleForm.renewNumber;
        month = month.toString().padStart(2, "0"); //
        var day = date
          .getDate(this.ruleForm.startDate)
          .toString()
          .padStart(2, "0"); //; // 获取日期
        if (month > 12) {
        }
        this.ruleForm.endDate = year + "-" + month + "-" + day;
      }
    },
    DepositQuantity(val) {
      this.ruleForm.renewTypeCode = 2;
      console.log(this.ruleForm.renewTypeCode);
      if (this.ruleForm.renewTypeCode === 1) {
        if (this.ruleForm.renewUnit === "年") {
          var date = new Date(this.ruleForm.startDate);
          var year = date.getFullYear();
          year += val;
          var month = (date.getMonth(this.ruleForm.startDate) + 1)
            .toString()
            .padStart(2, "0"); //
          var day = date
            .getDate(this.ruleForm.startDate)
            .toString()
            .padStart(2, "0"); //; // 获取日期
          this.ruleForm.endDate = year + "-" + month + "-" + day;

          this.ruleForm.itemCharge =
            this.ruleForm.renewNumber * this.depositCasePrice;

          this.ruleForm.itemCharge = this.ruleForm.itemCharge.toFixed(2);
        } else if (this.ruleForm.renewUnit === "月") {
          var date = new Date(this.ruleForm.startDate);
          var year = date.getFullYear();
          var month = date.getMonth(this.ruleForm.startDate) + 1;
          month += val;
          month = month.toString().padStart(2, "0"); //
          var day = date
            .getDate(this.ruleForm.startDate)
            .toString()
            .padStart(2, "0"); //; // 获取日期
          if (month > 12) {
            month = 0;
            month += val;
            month = month.toString().padStart(2, "0"); //
            year = date.getFullYear(this.ruleForm.startDate) + 1;
            // this.ruleForm.endDate = year + "-" + month + "-" + day;
          }
          this.ruleForm.endDate = year + "-" + month + "-" + day;
          this.ruleForm.itemCharge =
            this.ruleForm.renewNumber * (this.depositCasePrice / 12);
          this.ruleForm.itemCharge = this.ruleForm.itemCharge.toFixed(2);
        }
      } else if (this.ruleForm.renewTypeCode === 2) {
        if (this.ruleForm.renewUnit === "年") {
          var date = new Date(this.ruleForm.startDate);
          var year = date.getFullYear();
          year += val;
          var month = (date.getMonth(this.ruleForm.startDate) + 1)
            .toString()
            .padStart(2, "0"); //
          var day = date
            .getDate(this.ruleForm.startDate)
            .toString()
            .padStart(2, "0"); //; // 获取日期
          this.ruleForm.endDate = year + "-" + month + "-" + day;
          this.ruleForm.itemCharge = this.ruleForm.renewNumber * (5 * 12);
          this.ruleForm.itemCharge = this.ruleForm.itemCharge.toFixed(2);
        } else if (this.ruleForm.renewUnit === "月") {
          var date = new Date(this.ruleForm.startDate);
          var year = date.getFullYear();
          var month = date.getMonth(this.ruleForm.startDate) + 1;
          month += val;
          month = month.toString().padStart(2, "0"); //
          var day = date
            .getDate(this.ruleForm.startDate)
            .toString()
            .padStart(2, "0"); //; // 获取日期
          if (month > 12) {
            month = 0;
            month += val;
            month = month.toString().padStart(2, "0");
            year = date.getFullYear(this.ruleForm.startDate) + 1;
            // this.ruleForm.endDate = year + "-" + month + "-" + day;
          }

          this.ruleForm.endDate = year + "-" + month + "-" + day;
          this.ruleForm.itemCharge = this.ruleForm.renewNumber * 5;
        }
      }
    },
    // -------------------------------------------------------------
    age(type) {
      let nametype;
      if (this.copydictionary.age_type && this.copydictionary.age_type.length) {
        this.copydictionary.age_type.forEach((item) => {
          if (item.dataCode == type) {
            nametype = item.dataText;
          }
        });
        this.ruleForm.funeralDead.deadAge = "";
        if (nametype == "未知") {
          this.ruleForm.funeralDead.deadAge = "未知";
        }
      }
    },
    //年龄变化触发死亡日期变化
    ageChange(type, age) {
      let nametype;
      this.copydictionary.age_type.forEach((item) => {
        if (item.dataCode == type) {
          nametype = item.dataText;
        }
      });
      if (this.ruleForm.funeralDead.birthDate) {
        if (nametype == "月") {
          //月
          let birthData = Date.parse(this.ruleForm.funeralDead.birthDate);
          this.ruleForm.funeralDead.deathDate = new Date(
            age * 30 * 24 * 3600 * 1000 + birthData
          );
        } else if (nametype == "年") {
          //年
          let birthData = Date.parse(this.ruleForm.funeralDead.birthDate);
          this.ruleForm.funeralDead.deathDate = new Date(
            age * 365 * 24 * 3600 * 1000 + birthData
          );
        }
      }
    },
    //年龄限制

    //去掉左右空格
    trim(str) {
      if (str == null) {
        return "";
      }
      return str.replace(/^\s*(.*?)[\s\n]*$/g, "$1");
    },

    //数据读取
    ReadData() {
      let postData = {
        businessCode: this.businessCode,
      };
      this.loading = true;
      Type["LoadDepositRegisterWithBusiness"](postData).then((response) => {
        const { data } = response;
        if (!data) {
          this.loading = false;
          this.$message(response.message);
          return;
        }

        data.startDate = "";
        data.renewUnit = "";
        data.renewNumber = "";
        data.endDate = "";
        data.itemCharge = "";

        this.ruleForm = data;

        this.$store
          .dispatch("user/setbusinessCode", this.businessCode)
          .catch(() => console.log("promise catch err"));
        this.loading = false;

        Type["loadCremainsRenew"](postData).then((response) => {
          const { data } = response;
          if (!data) {
            this.loading = false;
            this.$message("数据读取失败");
            return;
          }
          this.ruleForm.renewTypeCode =
            data.depositBusinessItem.depositTypeCode; //1长期2短期
          this.ruleForm.startDate = data.depositBusinessItem.depositDueDate;
          this.ruleForm.depositCasePrice = this.depositCasePrice =
            data.depositBusinessItem.depositCasePrice;
          this.ruleForm.depositCaseId = data.depositBusinessItem.depositCaseId;
          // depositBusinessItem;
          console.log(this.depositCasePrice, 777);
          this.loading = false;
        });

        this.getList()
      });
    },
    getList() {
      Type["loadDepositCharges"]({
        businessCode: this.businessCode,
      }).then((response) => {
        const { data } = response;
        if (!data) {
          this.loading = false;
          this.$message("数据读取失败");
          return;
        }

        data.depositRenewItems.forEach((item) => {
          if (item.asSettled) {
            item.asSettled = "已结算";
          } else {
            item.asSettled = "未结算";
          }
        });
        this.tableData = data.depositRenewItems;
        this.chargeItems = data.chargeItems;

      });
    },
    searchData() {
      if (!this.businessCode) {
        this.$message("请输入业务编码");
        return;
      }
      //去除左右空格
      this.businessCode = this.trim(this.businessCode);
      this.ReadData();
    },
    //新增逝者火化档案

    // submitForm(formName) {
    //   this.$refs[formName].validate((valid) => {
    //     if (valid) {
    //       alert("submit!");
    //     } else {
    //       // console.log('error submit!!');
    //       return false;
    //     }
    //   });
    // },
    //逝者信息保存方法
    Save(route) {
      //验证非空
      if (Date.now() - this.onpresscTime > 2000) {
        this.onpresscTime = Date.now();
        console.log(Date.now());
      } else {
        return;
      }

      //表单验证
      this.$refs["homeRuleForm"].validate((valid) => {
        // alert(valid);
        // return
        if (valid) {
          this.saveFlag = true;
          let {
            businessCode,
            startDate,
            endDate,
            renewUnit,
            renewNumber,
            itemCharge,
            depositCaseId,
            depositCasePrice,
            remark,
          } = this.ruleForm;

          Type["saveCremainsRenew"]({
            businessCode,
            startDate,
            endDate,
            renewUnit,
            renewNumber,
            itemCharge,
            depositCaseId,
            depositCasePrice,
            remark,
          }).then((response) => {
            this.saveFlag = false;
            console.log(response.code, 555);
            if (response.code) {
              this.saveFlag = false;
              this.$message("保存数据成功");
               this.getList()
              return;
            } else {
              this.saveFlag = false;
            }

            //查询成功后拍照备案等按钮可显

            this.$message("保存数据成功");
          });
        }
      });
    },

    PhotoArchival() {
      this.$router.push("PhotoArchival");
    }, //打印逝者二维码
    //禁用行政区划

    //加载省市县

    //加载用户信息 洽谈元

    //加载街道信息

    //加载村信息
    //加载街道

    //拼音检索开始
    //拼音或中文检索
    PinyinMatchnation(val) {
      if (val) {
        let result = [];
        this.dictionary.nation.filter((item) => {
          if (item.dataTextAbbr.indexOf(val) != -1) {
            result.push(item);
          } else if (item.dataText && item.dataText.indexOf(val) != -1) {
            result.push(item);
          }
          this.copydictionary.nation = result;
        });
      } else {
        this.copydictionary.nation = JSON.parse(
          JSON.stringify(this.dictionary.nation)
        );
      }
    },
  },
  watch: {
    /*省市*/
    "ruleForm.funeralDead.provinceId"() {
      if (this.$refs.refHandle) {
        this.$refs.refHandle.dropDownVisible = false; //监听值发生变化就关闭它
      }
    },
    dictionary() {
      let dicData = this.dictionary;
      this.dictionary = dicData;
      this.copydictionary = JSON.parse(JSON.stringify(dicData));
    },
    "ruleForm.funeralDead.townId"() {
      if (this.ruleForm.funeralDead.townId) {
        this.loadvillage();
      }
    },
    businessCodeParam() {
      if (this.businessCodeParam) {
        this.searchData();
      }
    },
  },
};
</script>
<style>
/*.cascader .el-form-item__label{*/
/*width: 9vw!important;*/
/*}*/
.cascader .el-input,
.cascader .select .el-input {
  width: 25.6vw !important;
  min-width: 40px;
}

.lineheight label {
  line-height: 20px !important;
  letter-spacing: 3px;
}

.streetwidth,
.streetwidth input,
.streetwidth .el-input,
.streetwidth .el-select {
  width: 7vw !important;
  min-width: 120px !important;
}

.agewidth,
.agewidth input,
.agewidth .el-input {
  width: 5vw !important;
  min-width: 90px !important;
  overflow: hidden;
}

.input-with-select .el-input-group__prepend {
  background-color: #fff;
}

.PageContent .zm .el-input,
.PageContent .zm .el-select {
  width: 25.6vw;
  min-width: 40px;
}

.marginbottom0 .el-form-item {
  margin-bottom: 0px;
}
.home .el-textarea__inner {
  line-height: 2;
  min-height: 70px !important;
}
.home .el-select .el-input__inner {
  cursor: pointer;
  padding-right: 2px;
  text-align: left;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
<style scoped>
.home {
  color: #606266;
}
.w1230 {
  width: 72.5vw !important;
  min-width: 40px !important;
}

.w425 {
  width: 25.6vw;
  min-width: 40px;
}
.w50 {
  width: 57vw;
  min-width: 40px;
}
.letter2 {
  letter-spacing: 5px;
}

.el-input__inner {
  border: none;
}

.PageItem1 /deep/ .el-input__inner {
  border: 0px solid;
  background-color: #fff;
  color: #000;
}
</style>
